<?php

namespace App\Http\Controllers\HttpAgent;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Common\ErrorDefine;
use App\Http_ip;
use Redis;


class HttpAgentController extends Controller
{
    private  $params = [];
    private  $content = '';



//    private static $handler;
//    var $redis_;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
//    public function __construct()
//    {
//
//        $this->redis_ = new Redis();
//        $this->redis_->connect("127.0.0.1", "6379");
//
//    }
//
//    function __destruct()
//    {
//        if($this->redis_ != null) {
//            $this->redis_->close();
//        }
//    }


    /**
     * @param Request $request
     * 添加http代理IP 数据
     */
    public function addHttpAgentIpListData(Request $request)
    {

        $file = $request->file('server_name');
        self::fwrite($file);
        $content = file_get_contents($file->getRealPath());
        $originalName = $file->getClientOriginalName();

        $this->params['domain'] = substr($originalName,0,strripos($originalName,'.'));

        $result = explode(',',trim($content,','));
        if(!empty($result)){
            foreach ($result as $value)
            {
                try{
                    $ret = explode('--',$value);
                    $this->params['ip'] = substr($ret[0],0,strripos($ret[0],'/'));
                    $this->params['port'] = self::getIpPort($ret[1]);
                    Http_ip::insert($this->params);
                }catch (\Exception $e){
                }
            }
        }

    }




    static function getIpPort($ret){
        $ip_port = '';
        if(preg_match('/\d+/',$ret,$arr)){
            $ip_port =  $arr[0];
        }

        switch (strlen($ip_port)){
            case '1':$ip_port = '100'.$ip_port;break;
            case '2':$ip_port = '10'.$ip_port;break;
            case '3':$ip_port = '1'.$ip_port;break;
            default:$ip_port;
        }

        return $ip_port;
    }





    static function fwrite($data){

        $file=storage_path('logs/upload.log');
        $myFile = fopen($file, "a+") or die("Unable to open file!");
        $data = json_encode($data);
        $txt = $data."\n";
        fwrite($myFile, $txt);
        fclose($myFile);
    }


    
}












